package com.sigmatrix.h5.web.ins;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.sigmatrix.h5.components.FeignManager;
import com.sigmatrix.h5.components.RedisClient;
import com.sigmatrix.h5.entity.DisDealerAcct;
import com.sigmatrix.h5.entity.Enterprise;
import com.sigmatrix.h5.service.DisDealerAcctService;
import com.sigmatrix.h5.service.EnterpriseService;
import com.sigmatrix.h5.utils.CommonUtils;
import com.sigmatrix.h5.utils.Constants;
import com.sigmatrix.h5.web.Result;
import com.sigmatrix.h5.web.mode.Login;
import com.sigmatrix.sc.jdbc.common.lang.Session;
/**
 * 
 *@ClassName: LoginInterceptor
 *@Description: 验证登录拦截器
 *@author MH
 *@date 2017年9月25日 下午2:25:36
 */
@Component
public class InsInterceptor implements HandlerInterceptor{
	
	private Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	private RedisClient redisClient;
	
	@Autowired
	private FeignManager feignManager;
	
	
	@Autowired
	private EnterpriseService enterpriseService;
	
	@Autowired
	private DisDealerAcctService disDealerAcctService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object paramObject) throws Exception {
		response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		
		if (request.getRequestURI().contains("/rebate/dealers/v2/api/login/type/")) {
			return true;
		}
		
		if(request.getRequestURI().contains("/shop/reg/audit")) return h5(request, response);
		
		if(request.getRequestURI().contains("/rebate/shop/api/regist")) return h5(request, response);
		
		if(request.getRequestURI().contains("/h5/")) return h5(request, response);
		//如果是登录就放行
		if(request.getRequestURI().matches("^/(ins|rebate)/.*(?<!sms)/(login|vercode|)(/v2)?$")) return true;
		if(request.getRequestURI().matches("^/rebate/dealers/api/info$")) return true;
		if(request.getRequestURI().matches("^/rebate/regist/api/(query|regist)$") 
				|| request.getRequestURI().startsWith("/open/")) {
			return h5(request, response);
		}
		//验证token
		response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		String token = request.getParameter("token");
		if(StringUtils.isBlank(token)){
			//如果是短信验证码就通过token跟eseId来验证
			if("/rebate/api/sms/vercode".equals(request.getRequestURI())){
				return h5(request, response);
			}
			response.getWriter().write(Result.error(HttpStatus.SC_UNAUTHORIZED+"","token不能为空").toString());
			return false;
		}
		logger.info(String.format("url:[%s],token:[%s]", request.getRequestURI(),token));
		if(request.getRequestURI().matches("^/(ins|rebate)/.*/logout$"))return true;
		String loginStr = redisClient.get(token);
		if(StringUtils.isBlank(loginStr)){
			response.getWriter().write(Result.error(HttpStatus.SC_UNAUTHORIZED+"","token过期").toString());
			return false;
		}
		try{
			Login login = JSONObject.parseObject(loginStr, Login.class);
			login.setTablePreffix(login.getEseCode());
			//开发用
//			login.setTablePreffix("sigmatrix");
			Session.set(login);
		}catch(Exception e){
			e.printStackTrace();
			response.getWriter().write(Result.error("登录出错").toString());
			return false;
		}
		return true;
	}

	/**
	 * 门店注册
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	private boolean registShop(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String promotionCode = request.getParameter("promotionCode");//
		if(StringUtils.isBlank(promotionCode)){
			response.getWriter().write(Result.error("promotionCode不能为空").toString());
			return false;
		}
		//业务员
		DisDealerAcct disDealerAcct = disDealerAcctService.findByPromotionCode(promotionCode);
		Enterprise enterprise = null;
		if(disDealerAcct!=null){
			 enterprise = enterpriseService.findByBasicModuleId(disDealerAcct.getBasicModuleId());
		}else{
			//经销商
			enterprise = feignManager.getEnterpriseBy(promotionCode);
		}

		if(CommonUtils.isEmpty(enterprise)){
			response.getWriter().write(Result.error("没有查询到企业").toString());
			return false;
		}
		if(StringUtils.isBlank(enterprise.getCode())){
			response.getWriter().write(Result.error("无效的企业，没有编码").toString());
			return false;
		}
		if(enterprise.getStatus() != Constants.STATUS_ENABLE){
			response.getWriter().write(Result.error("无效的企业，已经禁用").toString());
			return false;
		}
		
		Login login = new Login();
		login.setTablePreffix(enterprise.getCode());
		login.setEseId(enterprise.getId());
		login.setEseCode(enterprise.getCode());
		Session.set(login);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse,
			Object paramObject, ModelAndView paramModelAndView) throws Exception {
		Session.clear();
		
	}

	@Override
	public void afterCompletion(HttpServletRequest paramHttpServletRequest,
			HttpServletResponse paramHttpServletResponse, Object paramObject, Exception paramException)
			throws Exception {
		
	}

	private boolean h5(HttpServletRequest request,HttpServletResponse response) throws IOException {
		if(request.getRequestURI().matches("^/rebate/dealers/api/h5/reset/.*$")) return true;
		//验证企业
		String eseId = request.getParameter("eseId");
		logger.info(String.format("url:[%s],eseId:[%s]", request.getRequestURI(),eseId));
		if(StringUtils.isBlank(eseId)){
			response.getWriter().write(Result.error("eseId不能为空").toString());
			return false;
		}
		try{
			Enterprise enterprise = enterpriseService.findByBasicModuleId(Integer.parseInt(eseId));
			if(CommonUtils.isEmpty(enterprise)){
				response.getWriter().write(Result.error("没有查询到企业").toString());
				return false;
			}
			if(StringUtils.isBlank(enterprise.getCode())){
				response.getWriter().write(Result.error("无效的企业，没有编码").toString());
				return false;
			}
			if(enterprise.getStatus() != Constants.STATUS_ENABLE){
				response.getWriter().write(Result.error("无效的企业，已经禁用").toString());
				return false;
			}
			Login login = new Login();
			login.setTablePreffix(enterprise.getCode());
			login.setEseId(enterprise.getId());
			login.setEseCode(enterprise.getCode());
			Session.set(login);
			return true;
		}catch(NumberFormatException e){
			response.getWriter().write(Result.error("eseId错误").toString());
			return false;
		}
	}

}
